/**
 * Created by zhaobo on 2016/12/22.
 */
import React, {Component} from "react";
import {Image, StyleSheet, ListView, Text, View, NativeModules, ActivityIndicator, RefreshControl} from "react-native";

const Toast = NativeModules.ToastAndroid;
const MOCKED_MOVIES_DATA = [
  {title: '标题', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];
const REQUEST_URL = 'http://192.168.0.118:8081/movie.json';

var resultsCache = {
  dataForQuery: [],
  nextPageNumberForQuery: {},
  totalForQuery: {},
};


export default class Movie extends Component {
  constructor(props) {
    super(props);   //这一句不能省略，照抄即可
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loadState: 1,// 1加载中  2显示  3空数据  4错误
      error: '',
      isLoadingTail: false,
      isRefreshing: false,
    };
    // 在ES6中，如果在自定义的函数里使用了this关键字，则需要对其进行“绑定”操作，否则this的指向不对
    // 像下面这行代码一样，在constructor中使用bind是其中一种做法（还有一些其他做法，如使用箭头函数等）
    this.fetchData = this.fetchData.bind(this);
    this.renderFooter = this.renderFooter.bind(this);
    this.hasMore = this.hasMore.bind(this);
    this.onEndReached = this.onEndReached.bind(this);
    this._onRefresh = this._onRefresh.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  render() {
    if (this.state.loadState === 1) {
      return this.renderLoadingView();
    } else if (this.state.loadState === 2) {
      return (
        <ListView
          renderSeparator={this.renderSeparator}// 渲染每行间的线
          dataSource={this.state.dataSource}// 数据源
          renderFooter={this.renderFooter}// 页头与页脚会在每次渲染过程中都重新渲染
          renderRow={this.renderMovie}// 从数据源渲染
          onEndReached={this.onEndReached}// 下拉到底部
          style={styles.listView}
          refreshControl={
          <RefreshControl
            refreshing={this.state.isRefreshing}
            onRefresh={this._onRefresh}
            tintColor="#ff0000"
            title="Loading..."
            titleColor="#00ff00"
            colors={['#ff0000', '#00ff00', '#0000ff']}
            progressBackgroundColor="#ffff00"
          />
          }
        />
      );
    } else if (this.state.loadState === 3) {
      return this.renderNothingView();
    } else if (this.state.loadState === 4) {
      return this.renderErrorView();
    }
  }

  _onRefresh() {
    this.setState({
      isRefreshing: true,
    });
    setTimeout(() => {
      this.setState({
        isRefreshing: false,
      });
    }, 5000);
  }

  onEndReached() {
    this.setState({
      isLoadingTail: true,
    });
    this.fetchData();
  }

  hasMore() {
    return true;
  }

  renderFooter() {
    if (!this.hasMore() || !this.state.isLoadingTail) {
      return <View style={styles.scrollSpinner}/>;
    }
    return <ActivityIndicator style={styles.scrollSpinner}/>;
  }

  renderSeparator(sectionID: number | string,
                  rowID: number | string,
                  adjacentRowHighlighted: boolean) {
    var style = styles.rowSeparator;
    if (adjacentRowHighlighted) {
      style = [style, styles.rowSeparatorHide];
    }
    return (
      <View key={'SEP_' + sectionID + '_' + rowID} style={style}/>
    );
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => {
        if (!response.ok && response.status != 200) {
          console.error(response);
          return "";
        } else {
          return response.json();
        }
      })
      .then((responseData) => {
        if (!responseData) {
          this.setState({
            loadState: 4,
            err: '数据为空',
          });
        } else {
          // 注意，这里使用了this关键字，为了保证this在调用时仍然指向当前组件，我们需要对其进行“绑定”操作
          console.log("" + responseData.total);
          if (!responseData.movies) {
          } else {
            var moviesForQuery = resultsCache.dataForQuery.slice();
            for (var i in responseData.movies) {
              moviesForQuery.push(responseData.movies[i]);
            }
            resultsCache.dataForQuery = moviesForQuery;
          }
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(resultsCache.dataForQuery),
            loadState: 2,
            isLoadingTail: false
          });
        }
      })
      .catch((error) => {
        console.error(error);
      });
  }

  renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text>
          正在加载电影数据……
        </Text>
      </View>
    );
  }

  renderMovie(movie) {
    return (
      <View style={styles.container}>
        <Image source={{uri: movie.posters.thumbnail}}
               style={styles.thumbnail}/>
        <View style={styles.text}>
          <Text>{movie.title}</Text>
          <Text>{movie.year}</Text>
        </View>
      </View>
    );
  }

  renderNothingView() {
    let text = "没有数据";
    return (
      <View style={[styles.container, styles.centerText]}>
        <Text style={styles.text}>{text}</Text>
      </View>
    );
  }

  renderErrorView() {
    return (
      <View style={[styles.container, styles.centerText]}>
        <Text style={styles.text}>{this.state.err}</Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  centerText: {
    alignItems: 'center',
  },
  listView: {
    marginTop: 10,
    marginBottom: 10,
    backgroundColor: '#F5FCFF',
  },
  thumbnail: {
    width: 53,
    height: 81,
  },
  text: {
    flex: 1,
    marginLeft: 10,
  },

  rowSeparator: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    height: 1,
    marginLeft: 4,
  },
  rowSeparatorHide: {
    opacity: 0.0,
  },
  scrollSpinner: {
    marginVertical: 20,
  },
});